package xin.shaozeming.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import xin.shaozeming.base.common.ex.CustomerException;
import xin.shaozeming.base.common.utils.ObjConverter;
import xin.shaozeming.base.dto.RoleUserDTO;
import xin.shaozeming.base.po.RolePO;
import xin.shaozeming.base.po.UserPO;
import xin.shaozeming.base.po.UserRolePO;
import xin.shaozeming.base.dao.UserRoleDao;
import xin.shaozeming.base.service.UserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xin.shaozeming.base.vo.UserRoleVO;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 邵泽铭
 * @since 2019-08-22
 */
@Transactional
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleDao, UserRolePO> implements UserRoleService {

    @Resource
    private UserRoleDao userRoleDao;

    /**
     * 查询用户列表的角色
     *
     * @param list
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public List<UserRoleVO> selectRoleUserIn(List<UserPO> list) {
        List<Integer> ids=new ArrayList<>();
        list.forEach(item->{
            ids.add(item.getId());
        });
        List<RoleUserDTO> dtoList= userRoleDao.selectRoleUserIn(ids);
        Stream<UserRoleVO> stream= list.stream().map(mapper->{
            List<RolePO> rolePOS=new ArrayList<>();
            dtoList.forEach(dto->{
                if(!StringUtils.isEmpty(dto.getRoleId())&& mapper.getId().equals(dto.getUserId())){
                    RolePO rolePO=new RolePO();
                    rolePO.setId(dto.getRoleId());
                    rolePO.setRoleName(dto.getRoleName());
                    rolePOS.add(rolePO);
                }
            });
            UserRoleVO userVO=ObjConverter.convert(mapper,UserRoleVO.class);
            userVO.setRoles(rolePOS);
            return userVO;
        });
        return stream.collect(Collectors.toList());
    }


    /**
     * 更新用户角色
     *
     * @param userId
     * @param list
     * @return
     */
    @Override
    public boolean updateUserRoleByRole(Integer userId, List<UserRolePO> list) {
        QueryWrapper<UserRolePO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        userRoleDao.delete(queryWrapper);
        if(saveBatch(list)){
            return  true;
        }else {
            throw  new CustomerException("更新用户角色失败");
        }

    }
}
